<template>
  <div>
    <AxiomToolbar>
      <AxiomButton type="primary" icon="Plus" @click="handleAdd(null)">新增顶级权限</AxiomButton>
    </AxiomToolbar>
    <AxiomTreeTable
      v-if="treeData.length"
      :data="treeData"
      :columns="columns"
      :loading="loading"
      @add="handleAdd"
      @edit="handleEdit"
      @delete="handleDelete"
    >
      <template #status="{ row }">
        <AxiomSwitch
          :model-value="row.status === 1"
          @change="(newState) => handleStatusChange(row, newState)"
        />
      </template>
    </AxiomTreeTable>
    <AxiomEmpty v-else description="无法加载权限数据" />
    
    <PermissionFormDialog
      :visible="dialogVisible"
      :mode="dialogMode"
      :initial-data="currentPermission"
      :parent-name="parentPermissionName"
      @close="dialogVisible = false"
      @success="handleSuccess"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, inject } from "vue";
import {
  AxiomTreeTable,
  AxiomEmpty,
  AxiomButton,
  AxiomToolbar,
  AxiomSwitch,
} from "axiom-view";
import {
  getPermissionTree,
  deletePermission,
  enablePermission,
  disablePermission
} from "@/api/system/permission";
import PermissionFormDialog from './PermissionFormDialog.vue';

const { notification, useConfirm } = inject('axiom-utils');
const { show: showConfirm } = useConfirm;

const treeData = ref([]);
const loading = ref(false);

const typeFormatter = (row, column, cellValue) => {
  const typeMap = {
    MENU: '菜单',
    BUTTON: '按钮'
  };
  return typeMap[cellValue] || cellValue;
};

const columns = ref([
  { prop: 'permission_name', label: '权限名称', width: 250 },
  { prop: 'permission_code', label: '权限标识' },
  { prop: 'type', label: '类型', width: 100, formatter: typeFormatter },
  { prop: 'icon', label: '图标', width: 100 },
  { prop: 'sort', label: '排序', width: 80 },
  { prop: 'status', label: '状态', width: 80, slot: 'status' },
]);
const dialogVisible = ref(false);
const dialogMode = ref('add');
const currentPermission = ref({});
const parentPermissionName = ref('顶级权限');
const permissionMap = new Map();

const refreshTable = async () => {
  loading.value = true;
  try {
    const response = await getPermissionTree();
    if (response && response.success) {
      permissionMap.clear();
      const data = response.data || [];
      const processNodes = (nodes) => {
        if (!nodes || !nodes.length) return;
        for (const node of nodes) {
          node.id = String(node.id);
          node.status = Number(node.status); // 确保 status 是数字
          permissionMap.set(node.id, node);
          if (node.children && node.children.length > 0) {
            processNodes(node.children);
          }
        }
      };
      processNodes(data);
      treeData.value = data;
    }
  } catch (error) {
    console.error("获取权限树失败:", error);
  } finally {
    loading.value = false;
  }
};

const handleAdd = (row) => {
  dialogMode.value = 'add';
  if (row) {
    currentPermission.value = { parent_id: row.id };
    parentPermissionName.value = row.permission_name;
  } else {
    currentPermission.value = { parent_id: '0' };
    parentPermissionName.value = '顶级权限';
  }
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  dialogMode.value = 'edit';
  currentPermission.value = { ...row };
  const parentNode = permissionMap.get(String(row.parent_id));
  parentPermissionName.value = parentNode ? parentNode.permission_name : '顶级权限';
  dialogVisible.value = true;
};

const handleDelete = async (row) => {
  await showConfirm({
    title: '确认删除',
    content: `您确定要删除权限【${row.permission_name}】吗？如果它包含子权限，将会一并删除。`,
    type: 'error',
    onConfirm: async () => {
      await deletePermission(row.id);
      notification.success({ title: '成功', message: '删除成功' });
      await refreshTable();
    }
  });
};

const handleStatusChange = async (row, newState) => {
  const originalStatus = row.status;
  row.status = newState ? 1 : 0;
  
  try {
    const action = newState ? enablePermission : disablePermission;
    await action(row.id);
    notification.success({ title: '成功', message: '状态更新成功' });
    // 状态更新后可能影响子节点，最好刷新整个树
    await refreshTable();
  } catch (error) {
    row.status = originalStatus;
    console.error('更新权限状态失败:', error);
  }
};

const handleSuccess = () => {
  dialogVisible.value = false;
  refreshTable();
};

onMounted(async () => {
  await refreshTable();
});
</script>
